package com.lingkang.sales.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lingkang.sales.common.val.HttpCode;
import com.lingkang.sales.data.dto.ResponsePageResult;
import com.lingkang.sales.data.dto.ResponseResult;
import com.lingkang.sales.data.entity.SaPermission;
import com.lingkang.sales.data.entity.SaRole;
import com.lingkang.sales.data.mapper.SaPermissionMapper;
import com.lingkang.sales.data.mapper.SaRoleMapper;
import com.lingkang.sales.service.AuthService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;

/**
 * @author linke
 * @date 2020/11/14 20:56
 * @description
 */
@Service
public class AuthServiceImpl implements AuthService {

  @Autowired
  private SaRoleMapper saRoleMapper;
  @Autowired
  private SaPermissionMapper saPermissionMapper;

  @Override
  public List<SaRole> getRoles(String username) {
    return saRoleMapper.getRoles(username);
  }

  @Override
  public boolean hasPermission(String targetDomainObject,
      String permission) {
    String[] per = permission.split(":");
    String role = per[0];
    String action = per[1];
    SaPermission has = saPermissionMapper.getPermissions(role);
    if (has == null) {
      return false;
    }
    AntPathMatcher path = new AntPathMatcher();
    //path.match("/*","/admin/admin");   true
    if (path.match(has.getSource(), targetDomainObject) && has.getAction().contains(action)) {
      return true;//权限允许
    }
    return false;
  }

  @Override
  @Transactional
  public ResponseResult addRole(String role, String desc) {
    if (saRoleMapper.countRoleName(role) > 0) {
      return new ResponseResult(HttpCode.FAIL, "已经存在的角色名！无法添加");
    }
    SaRole saRole = new SaRole();
    saRole.setCreateTime(new Date());
    saRole.setDescription(desc);
    saRole.setRoleName(role);
    saRoleMapper.insertSelective(saRole);
    return new ResponseResult(HttpCode.OK, "角色添加成功");
  }

  @Override
  public SaPermission getPermission(String roleName) {
    return saPermissionMapper.getPermissions(roleName);
  }

  @Override
  public ResponsePageResult getRoleList(Integer page, Integer size, String search) {
    Page pages = PageHelper.startPage(page, size);
    if (StrUtil.isNotBlank(search)){
      search=String.format("%%%s%%",search);
    }else{
      search=null;
    }
    List<SaRole> list = saRoleMapper.getRoleList(search);
    return new ResponsePageResult(HttpCode.OK, page, size, pages.getTotal(), list);
  }

  @Override
  @Transactional
  public ResponseResult roleDelete(Integer id) {
    saRoleMapper.deleteByPrimaryKey(id);
    return new ResponseResult(HttpCode.OK, "删除角色成功！");
  }

  @Override
  @Transactional
  public ResponseResult roleUpdate(Integer id, String roleName, String description) {
    SaRole saRole = new SaRole();
    saRole.setUpdateTime(new Date());
    saRole.setRoleName(roleName);
    saRole.setDescription(description);
    saRole.setId(id);
    saRoleMapper.updateByPrimaryKeySelective(saRole);
    return new ResponseResult(HttpCode.OK, "角色更新！");
  }

  @Override
  public ResponsePageResult permissionList(Integer page, Integer size, String search) {
    Page pages = PageHelper.startPage(page, size);
    if (StrUtil.isNotBlank(search)) {
      search = String.format("%%%s%%", search);
    } else {
      search = null;
    }
    List<SaPermission> list = saPermissionMapper.permissionList(search);//%%编译：%
    return new ResponsePageResult(HttpCode.OK, page, size, pages.getTotal(), list);
  }

  @Override
  @Transactional
  public ResponseResult permissionUpdate(String roleName, String source, String action, String description) {
    SaPermission permission = new SaPermission();
    permission.setRoleName(roleName);
    permission.setSource(source);
    permission.setDescription(description);
    if (StrUtil.isNotBlank(action)) {
      StringBuffer act = new StringBuffer();
      if (action.indexOf("r") != -1) {
        act.append("r");
      }
      if (action.indexOf("w") != -1) {
        act.append("w");
      }
      permission.setAction(act.toString());
    }
    saPermissionMapper.updateByPrimaryKeySelective(permission);
    return new ResponseResult(HttpCode.OK, "更新成功！");
  }

  @Override
  public List<String> getUserExistRole() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> roles = authentication.getAuthorities();
    if (roles.isEmpty()) {
      return null;
    }
    List<String> role = new ArrayList<>();
    for (GrantedAuthority r : roles) {
      role.add(r.getAuthority());
    }
    return role;
  }

  @Override
  @Transactional
  public ResponseResult permissionDelete(String roleName) {
    saPermissionMapper.deleteByPrimaryKey(roleName);
    return new ResponseResult(HttpCode.OK, "删除成功！");
  }

  @Override
  public List<SaRole> getRoleListExcludeExist() {
    return saRoleMapper.getRoleListExcludeExist();
  }

  @Override
  @Transactional
  public ResponseResult permissionAdd(String roleName, String source, String action, String description) {
    SaPermission p = saPermissionMapper.getPermissions(roleName);
    if (p != null) {
      return new ResponseResult(HttpCode.FAIL, "该角色已经授权，无法再授权了！");
    }
    SaPermission permission = new SaPermission(roleName, source, action, description);
    saPermissionMapper.insertSelective(permission);
    return new ResponseResult(HttpCode.OK, "添加成功！");
  }

}
